import {Box2,Box3,BufferGeometry,Object3D,Vector2, Vector3} from "three/src/Three";
import Const from "../../application/constants/Const";
import { Point } from "../../renderExtension/types/Point";
import GeoUtils from "../../utils/GeoUtils";
import { App, Circle, HtmlMarker } from "../../Engine";

/**
* 点缓冲区分析
*/
export default class CircleBufferAnalysis {
    private rangeArray = []; //缓冲区分析对象数据
    private bufferDistance; //缓冲范围
    private circle: Circle; //缓冲区圆

    /**
     * 构建圆缓存分析
     * @param param 构建圆缓冲区需要用到的参数
     * @param param.bufferDistance 缓冲范围
     * @param param.objects 分析对象
     * @param param.circle 缓冲区圆
     */
    public constructor(param: { bufferDistance: number, objects: Array<Object3D>, circle: Circle}) {
        this.bufferDistance = (param.bufferDistance === undefined)?100:param.bufferDistance;
        this.circle = param.circle;

        this.updateCircleRadius();
        this.initRangeArray(param);
    }

    private initRangeArray(cfg){
        let self = this;
        cfg.objects.forEach(element => {
            let range:{ minX: number, minY: number, maxX: number, maxY: number } = { minX: 0, minY: 0, maxX: 0, maxY: 0 };

            if(element instanceof HtmlMarker){
                range.minX = element.position.x;
                range.minY = element.position.y;
                range.maxX = element.position.x;
                range.maxY = element.position.y;
            }else{
                var box = new Box3();
                box.setFromObject(element);
                
                range.minX = box.min.x;
                range.minY = box.min.y;
                range.maxX = box.max.x;
                range.maxY = box.max.y;
            }

            self.rangeArray.push(range);
        });
    }

    public updateCircleRadius(){
        let radius = this.circle.getParam().radius + this.bufferDistance;
        this.circle.setRadius(radius);
    }

    public bufferAnalysis(){
        let result = [];
        let circleCenter = this.circle.getParam().center;
        let center = new Vector2(circleCenter.x, circleCenter.y);
        let radius = this.circle.getParam().radius;

        for (let i = 0; i < this.rangeArray.length; i++) {
            let isContain = false;
            let objectCenter = new Vector2((this.rangeArray[i].maxX + this.rangeArray[i].minX)/2, (this.rangeArray[i].maxY + this.rangeArray[i].minY)/2);

            let distance = objectCenter.distanceTo(center);
            if(distance <= radius){
                isContain = true;
            }
            
            result[i] = isContain;
        }
        return result;
    }

    public clear(){
        App.getInstance().remove(this.circle);
    }
}